package org.pay.pay.channel;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.pay.pay.service.RpcCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.pay.core.common.Exception.ServiceException;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.common.constant.RetEnum;
import org.pay.core.entity.MchChannel;
import org.pay.core.entity.PayChannel;
import org.pay.core.entity.PayOrder;

/**
 * @author: yangshancheng
 * @date: 17/12/24
 * @description:
 */
@Component
public abstract class BasePayment extends BaseService implements PaymentInterface {

    @Autowired
    public RpcCommonService rpcCommonService;

    @Autowired
    public PayConfig payConfig;

    public abstract String getChannelName();

    public JSONObject pay(PayOrder payOrder) {
        return null;
    }

    public JSONObject query(PayOrder payOrder) {
        return null;
    }

    public JSONObject close(PayOrder payOrder) {
        return null;
    }

    /**
     * 获取三方支付配置信息
     * 如果是平台账户,则使用平台对应的配置,否则使用商户自己配置的渠道
     * @param payOrder
     * @return
     */
    public String getPayParam(PayOrder payOrder) {
        String payParam = "";
        Long mchId = payOrder.getMchId();
        String channelId = payOrder.getChannelId();
        String appId = payOrder.getAppId();
        if(payOrder.getMchType() == MchConstant.MCH_TYPE_PLATFORM) {
            Integer passageId = payOrder.getPassageId();
            PayChannel payChannel;
            if(passageId != null) {
                payChannel = rpcCommonService.rpcPayChannelService.findByPassageAndChannelId(passageId, payOrder.getChannelId());
            }else {
                // 如果下单时没有指定渠道ID,则临时取一个
                payChannel = rpcCommonService.rpcPayChannelService.findByChannelId(payOrder.getChannelId());
            }
            if(payChannel != null) payParam = payChannel.getParam();
        }else if(payOrder.getMchType() == MchConstant.MCH_TYPE_PRIVATE) {
            MchChannel mchChannel = rpcCommonService.rpcMchChannelService.findByMACId(mchId, appId, channelId);
            if(mchChannel != null) payParam = mchChannel.getParam();
        }
        if(StringUtils.isBlank(payParam)) {
            throw new ServiceException(RetEnum.RET_MCH_CHANNEL_NOT_EXIST);
        }
        return payParam;
    }

}
